#!/bin/bash

# Source hadoop-env.sh
. $HADOOP_HOME/etc/hadoop/hadoop-env.sh

# Directory to find config artifacts
CONFIG_DIR="/opt/hadoop-config"

# Dfs.replication
REPLICATION=${REPLICATION:-2}
sed -i "s#REPLICATION#$REPLICATION#" ${CONFIG_DIR}/hdfs-site.xml

# Copy config files
for f in slaves core-site.xml hdfs-site.xml mapred-site.xml yarn-site.xml; do
    if [[ -e ${CONFIG_DIR}/$f ]]; then
        cp ${CONFIG_DIR}/$f ${HADOOP_CONF_DIR}/$f
    else
        echo "ERROR: Could not find $f in $CONFIG_DIR"
        exit 1
    fi
done

# Start service
command=$1
case $command in
    namenode)
        ${CONFIG_DIR}/wait

        . $HADOOP_LIBEXEC_DIR/hadoop-config.sh
        . $HADOOP_CONF_DIR/hadoop-env.sh

        if [[ ! -d $HADOOP_HOME/name/current ]]; then
            mkdir $HADOOP_HOME/name
            chown hadoop:hadoop $HADOOP_HOME/name
            echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME Init hdfs namenode -format."
            gosu hadoop $HADOOP_HOME/bin/hdfs namenode -format -force -nonInteractive
        fi

        echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME start namenode."
        exec gosu hadoop $HADOOP_HOME/bin/hdfs --config $HADOOP_CONF_DIR namenode
        ;;
    datanode)1
        ${CONFIG_DIR}/wait

        . $HADOOP_LIBEXEC_DIR/hadoop-config.sh
        . $HADOOP_CONF_DIR/hadoop-env.sh

        if [[ ! -d "$HADOOP_HOME/data/current" ]]; then
            mkdir $HADOOP_HOME/data
            chown hadoop:hadoop $HADOOP_HOME/data
        fi

        echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME start datanode."
        exec gosu hadoop $HADOOP_HOME/bin/hdfs --config $HADOOP_CONF_DIR datanode
        ;;
    nodemanager)
        ${CONFIG_DIR}/wait

        sed -i '/<\/configuration>/d' ${HADOOP_CONF_DIR}/yarn-site.xml
        cat >> ${HADOOP_CONF_DIR}/yarn-site.xml <<-EOF
	  <property>
	    <name>yarn.nodemanager.resource.memory-mb</name>
	    <value>${MY_MEM_LIMIT:-1024}</value>
	  </property>
	  <property>
	    <name>yarn.nodemanager.resource.cpu-vcores</name>
	    <value>${MY_CPU_LIMIT:-1}</value>
	  </property>
	EOF
        echo '</configuration>' >> ${HADOOP_CONF_DIR}/yarn-site.xml

        # nodemanager.local-dirs nodemanager.log-dirs
        #mkdir -p /var/log/hadoop-yarn /var/lib/hadoop-yarn
        #chown -Rf hadoop:hadoop /var/log/hadoop-yarn /var/lib/hadoop-yarn

        . $HADOOP_LIBEXEC_DIR/yarn-config.sh
        . $YARN_CONF_DIR/yarn-env.sh
        echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME start nodemanager."
        exec gosu hadoop $HADOOP_HOME/bin/yarn --config $HADOOP_CONF_DIR nodemanager
        ;;
    resourcemanager)
        ${CONFIG_DIR}/wait

        . $HADOOP_LIBEXEC_DIR/yarn-config.sh
        . $YARN_CONF_DIR/yarn-env.sh

        echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME start resourcemanager."
        exec gosu hadoop $HADOOP_HOME/bin/yarn --config $HADOOP_CONF_DIR resourcemanager
        ;;
esac

exec "$@"
